package com.zrh.jsd.web.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Api(tags = "类用途描述：ThreadLocal测试", value = "据说不显示,并且是真的")
@RestController
@RequestMapping("threadLocal")
public class ThreadLocalController {

    private ThreadLocal<Integer> currentUser = ThreadLocal.withInitial(() -> null);

    @ApiOperation("方法用途描述：测试threadlocal")
    @GetMapping("wrong")
    public Map wrong(@RequestParam("userId") Integer userId) {
        try {
            // 设置用户信息之前先查询一次ThreadLocal中的用户信息
            String before = Thread.currentThread().getName() + ":" + currentUser.get();
            // 设置用户信息到ThreadLocal
            currentUser.set(userId);
            // 设置用户信息之后再查询一次ThreadLocal中的用户信息
            String after = Thread.currentThread().getName() + ":" + currentUser.get();
            // 汇总输出两次查询结果
            Map result = new HashMap();
            result.put("before", before);
            result.put("after", after);
            return result;
        } finally {
            currentUser.remove();
        }
    }
}